# @Version        : 1.0
# @Update Time    : 2025/3/13 16:03
# @File           : scan_view.py
# @IDE            : PyCharm
# @Desc           : 文件描述信息
import asyncio

# views/scan_view.py
import flet as ft


class ScanView(ft.Stack):
    def __init__(self, page: ft.Page, params: dict = None):
        super().__init__()
        self.page = page
        self.params = params
        self.expand = True
        self._animate_active = True  # 控制动画循环的开关
        self.build_ui()


    def will_unmount(self):
        # 页面切换时停止动画
        self._animate_active = False

    def build_ui(self):
        # 背景层（摄像头预览占位）
        self.camera_preview = ft.Image(
            src="assets/discount_banner.png",  # 用户提供的扫描背景图
            fit=ft.ImageFit.COVER,
            expand=True
        )

        # 扫描框叠加层
        scan_overlay = ft.Container(
            content=ft.Column([
                ft.Text("将商品放入框内扫描",
                        size=20,
                        color=ft.colors.WHITE),
                ft.Container(
                    ft.ProgressRing(width=50, height=50, color=ft.colors.WHITE),
                    padding=20
                )
            ],
                horizontal_alignment=ft.CrossAxisAlignment.CENTER,
                spacing=20),
            alignment=ft.alignment.center,
            bgcolor=ft.colors.BLACK54,
            border_radius=10
        )

        # 扫描框线动画
        self.scan_line = ft.Container(
            height=2,
            width=250,
            top=300,
            left=60,
            bgcolor=ft.colors.GREEN_300,
            animate_position=1000,
            animate_opacity=300
        )

        # 扫描框图形
        scan_frame = ft.Container(
            width=300,
            height=300,
            border=ft.border.all(2, ft.colors.GREEN_300),
            border_radius=15,
            alignment=ft.alignment.center
        )

        self.controls = [
            self.camera_preview,
            ft.Container(scan_frame, alignment=ft.alignment.center),
            scan_overlay,
            self.scan_line
        ]

        # 启动扫描动画
        # self.start_scan_animation()
        # 修改扫描线初始位置
        self.scan_line = ft.Container(
            height=2,
            width=250,
            top=300,
            left=60,
            bgcolor=ft.colors.GREEN_300,
            animate_position=1000,
            animate_opacity=300,
            visible=False  # 初始隐藏
        )

    async def start_scan_animation(self):
        self.scan_line.visible = True
        self.scan_line.update()

        while self._animate_active and self.page:
            # 向下移动
            self.scan_line.top = 300
            self.scan_line.opacity = 1
            await self.scan_line.update_async()
            await asyncio.sleep(0.5)

            # 向上移动
            self.scan_line.top = 500
            self.scan_line.opacity = 0.5
            await self.scan_line.update_async()
            await asyncio.sleep(0.5)